package com.example.minademo.controller;

import com.example.minademo.entity.ErrorCode;
import com.example.minademo.entity.ResultData;
import com.example.minademo.entity.User;
import com.example.minademo.mina.UserSessionManager;
import com.example.minademo.service.impl.UserServiceImpl;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private Gson mGson;

    @Autowired
    private UserServiceImpl mUserService;


    @PostMapping(value = "/register")
    public String register(@RequestParam("name") String name,
                           @RequestParam("password") String password){


        User ou = mUserService.findUserByName(name);
        if(ou != null){
            return mGson.toJson(ResultData.error("用户名已存在",
                    ErrorCode.User.CODE_NAME_EXIST));
        }

        User user = new User();
        user.setName(name);
        user.setPassword(password);

        if(mUserService.saveUser(user)){
            return mGson.toJson(ResultData.success("注册成功",null));
        }else{
            return  mGson.toJson(ResultData.error("注册失败",ErrorCode.User.CODE_REGISTER_FALSE));
        }
    }

    @PostMapping(value = "/login")
    public String login(@RequestParam("name") String name,
                        @RequestParam("password") String password){
        User user = mUserService.findByNameAndPassword(name,password);
        if(user == null){
            return mGson.toJson(ResultData.error("用户名或密码错误",
                    ErrorCode.User.CODE_LOGIN_FAIL));
        }
        return mGson.toJson(ResultData.success("登录成功",user));

    }

    @PostMapping(value = "/bindSession")
    public String bindSession(@RequestParam("userId") Integer userId,
                              @RequestParam("sessionId") Long sessionId){
        User user = mUserService.findUserById(userId);
        if(user == null){
            return mGson.toJson(ResultData.error("用户不存在",ErrorCode.User.CODE_USER_NOT_EXIST));
        }

        UserSessionManager manager = UserSessionManager.getInstance();
        manager.addUserSession(userId,sessionId);
        return mGson.toJson(ResultData.success("绑定成功",null));
    }

}
